package com.basis.utils;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.basis.contants.ExceptionEnum;
import com.basis.exception.BizException;

/**
 * 工具类
 *
 * @author lxd
 */
public class ToolUtil {

    
    /**   
     * @Description:   生成指定长度的字母数字字符串
     * @param:         @param length
     * @param:         @return      
     * @return:        String   
     * @author:        lxd  
     * @date:          2019年11月26日 下午2:28:48     
     */  
    public static String getRandomString(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < length; ++i) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }

        return sb.toString();
    }

    
    /**   
     * @Description:   渲染json对象并返回给客户端
     * @param:         @param response
     * @param:         @param jsonObject      
     * @author:        lxd  
     * @date:          2019年11月26日 下午2:31:41     
     */  
    public static void renderJson(HttpServletResponse response, Object jsonObject) {
        try {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(jsonObject));
        } catch (IOException e) {
            throw new BizException(ExceptionEnum.SYSTEM_ERRO.getCode(), ExceptionEnum.SYSTEM_ERRO.getMessage());
        }
    }
}
